package cn.com.transfer.services;

import cn.com.transfer.utils.TransLog;
import flexjson.JSONSerializer;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.Record;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by SAMSUNG on 2015/9/7.
 */
public class TransFailed extends MsgHandlerService {
    private Logger logger = LoggerFactory.getLogger(TransFailed.class);
    public String handler(Map params) {
        Map rtn = new HashMap();
        String accountNo = (String) params.get("accountNo");
        Cnd cnd = Cnd.where("reverse", "=", 2).and("accountNo", "=", accountNo);
        if (params.get("action").equals("query")) {
            List<Record> query = dao.query("icbcQCLog", cnd);
            if (query.size() == 0) {
                rtn.put("success", false);
            }else {
                Integer money = 0;
                for (Record record : query) {
                    money += record.getInt("amount");
                }
                rtn.put("success", true);
                rtn.put("money", money);
            }
        }else if (params.get("action").equals("commit")) {
            logger.info("补充金额完成。");
            dao.update("icbcQCLog", Chain.make("reverse", 0), cnd);
            rtn.put("success", true);
        }else if (params.get("action").equals("back")) {
            logger.info("补充金额失败");
            Record customer = dao.fetch("tb_customer", Cnd.where("accountNo", "=", params.get("accountNo")));
            BigDecimal accLeftMoney = BigDecimal.valueOf(Double.valueOf(params.get("money").toString()) / -100);
            TransLog.addRechargeLog(customer, accLeftMoney, dao);
            dao.update("tb_customer", Chain.make("leftMoney", ((BigDecimal) customer.get("LeftMoney")).add(accLeftMoney)),
                    Cnd.where("accountNo", "=", customer.get("accountNo")));
            rtn.put("success", true);
        }
        return new JSONSerializer().serialize(rtn);
    }
}
